<?php

namespace app\admin\controller;

use think\Db;
use service\SmsService;

class Member extends Common
{
    protected $table = 'member';

    public function index()
    {
        $memberModel = model('common/member/Member');
        $where = [];
        if (input('?get.type')) {
            $type = input('get.type');
            switch ($type) {
                // 付费会员
                case 1:
                    $where[] = ['m1.level', 'eq', 2];
                    break;
                // 今日注册
                case 2:
//                    $where[] = ['', 'exp', Db::raw('FROM_UNIXTIME(`m1`.`create_time`,\'%Y-%m-%d\') = \'' . date('Y-m-d') . '\'')];
                    $where[] = ['m1.create_time', 'gt', strtotime(date('Y-m-d')) - 1];
                    break;
                // 用户性别
                case 3:
                case 4:
                    $where['m1.sex'] = $type - 2;
                    break;
                case 5:
                    $where['m1.video_verify'] = 1;
                    $where['m1.sex'] = 2;
                    break;
                case 6:
                    $where['m1.real_verify'] = 1;
                    $where['m1.sex'] = 1;
                    break;
                case 7:
                    $where['m1.real_verify'] = 1;
                    $where['m1.sex'] = 2;
                case 8:
                    $where['m1.identity'] = $memberModel::PARTNER;
                    break;
                // 用户ID
                case 'id':
                    $where['m1.' . $type] = input('get.text');
                    break;
                // 昵称或手机
                default:
                    $where[] = ['m1.' . $type, 'like', '%' . input('get.text') . '%'];
            }
        }
        $field = 'm1.id, m1.avatar, m1.sex, m1.province, m1.username, m1.nickname, m1.available_balance, m1.invite_code,m1.is_company,m1.video_verify,m1.create_time';
        $field .= ',m1.level_expire_time, m1.status, m1.last_login_time, m1.parent_id, m2.nickname parent_nickname, m2.username parent_username,a.name as city';
        $field .= ',m1.type,m1.identity';
        $field .= ',m_l.name as level_name';

        $data = $memberModel->getMemberList($where, $field, 'm1.id desc');
        $page = $memberModel->page_info->render();

        $this->assign('data', $data);
        $this->assign('page', $page);
        $this->assign('types', $memberModel->types);
        $this->assign('identitys', $memberModel->identitys);
        return $this->fetch();
    }

    public function add()
    {
        $memberModel = model('common/member/Member');

        if ($this->request->isAjax()) {
            $data = $this->request->post();

            $recommend_invite_code = $data['recommend_invite_code'];

            unset($data['recommend_invite_code']);
            if (isset($data['content_type_list'])) {
                $data['content_types'] = implode('/', $data['content_type_list']);
                unset($data['content_type_list']);
            }

            if (isset($data['expect_object_list'])) {
                $data['expect_object'] = implode('/', $data['expect_object_list']);
                unset($data['expect_object_list']);
            }

            $validate = validate('member');
            if (!$validate->check($data)) {
                return ['err' => $validate->getError()];
            }
            $id = $data['id'];
            unset($data['id']);
            $username = $memberModel->getVal('username', ['username' => $data['username']]);

            $levelModel = model('common/member/Level');
            if ($id > 0) {
                $member = $memberModel->getInfo(['id' => $id]);
                if (empty($member)) return ['err' => '用户不存在或已删除'];
                if (!empty($username) && $username != $member['username']) return ['err' => '用户手机已存在'];

                if (!empty($member['avatar'])) {
                    if ($data['avatar'] != $member['avatar']) {
                        $fileLogic = model('common/file/FileLogic', 'logic');
                        if ($fileLogic->fileExists($member['avatar'])) $fileLogic->deleteFile($member['avatar']);
                    }
                }


                $data['longitude'] = $longitude = $data['longitude'] ?? 113.2782112;
                $data['latitude'] = $latitude = $data['latitude'] ?? 23.13512111;
                $data['long_lat_geometry'] = Db::raw("geomfromtext('POINT({$longitude} {$latitude})')");
                if ($data['real_verify'] == 1 && $member['level'] < $levelModel::VERIFIY_LEVEL) $data['level'] = $levelModel::VERIFIY_LEVEL;  //升级到认证等级

                Db::startTrans();
                if ($member['parent_id'] == 0 && $member['is_company'] == 0 && !empty($recommend_invite_code)) { //无推荐人并且不是公司,邀请码提交

                    $inviteMember = $memberModel->getInfo(['invite_code' => $recommend_invite_code]);
                    if (empty($inviteMember)) {
                        Db::rollback();
                        return ['err' => '邀请人不存在'];
                    }

                    if ($data['identity'] == $memberModel::PARTNER) {
                        $up_list = $memberModel->getList(['id' => explode(',', $inviteMember['recommend_str']), 'identity' => $memberModel::PARTNER], 0);
                        if ($up_list) return ['err' => '上级存在合伙人，不能设置成合伙人'];

                        $down_partner = $memberModel->where('find_in_set(' . $member['id'] . ',recommend_str) and identity=' . $memberModel::PARTNER)->find();
                        if ($down_partner) return ['err' => '网体存在合伙人不能设置成合伙人'];
                    }

                    if ($inviteMember['status'] == 0) return ['err' => '邀请人被禁用'];
                    if ($inviteMember['is_company'] == 0 && $inviteMember['parent_id'] == 0) return ['err' => '邀请人无推荐人'];

                    $mid = $member['id'];
                    //更新单前用户的关系
                    $update_data = array_merge([
                        'parent_id' => $inviteMember['id'],
                        'recommend_dept' => $inviteMember['recommend_dept'] + 1,
                        'recommend_str' => empty($inviteMember['recommend_str']) ? $mid : $mid . ',' . $inviteMember['recommend_str'],
                        'invite_code' => $memberModel->createInviteCode()
                    ]);

                    if ($inviteMember['type'] == 1) $update_data['type'] = 2;

                    $update_data = array_merge($update_data, $data);

                    $isSave = $memberModel->editByID($mid, $update_data);
                    if (!$isSave) {
                        Db::rollback();
                        return ['err' => '邀请出错1'];
                    }

                    //更新推荐人，直推数量
                    $res = $memberModel->setValInc(['invite_code' => $recommend_invite_code], 'recommend_num', 1);
                    if (!$res) {
                        Db::rollback();
                        return ['err' => '更新推荐人错误'];
                    }
                } else {

                    if ($member['identity'] != $memberModel::PARTNER && $data['identity'] == $memberModel::PARTNER) {
                        //上级查找
                        $up_partner = $memberModel->getList(['id' => explode(',', $member['recommend_str']), 'identity' => $memberModel::PARTNER], 0);
                        if ($up_partner) return ['err' => '上级存在合伙人，不能设置成合伙人'];

                        $down_partner = $memberModel->where('find_in_set(' . $member['id'] . ',recommend_str) and identity=' . $memberModel::PARTNER)->find();
                        if ($down_partner) return ['err' => '网体存在合伙人不能设置成合伙人'];
                    }

                    $isSave = $memberModel->editByID($member['id'], $data);
                    if (!$isSave) {
                        Db::rollback();
                        return ['err' => '未做修改'];
                    }
                }

                if ($data['status'] == 0) model('common/member/TokenLogic', 'logic')->deleteToken($id); //禁用把用户踢下线


            } else {
                if (!empty($username)) return ['err' => '用户手机已存在'];
                $company = $memberModel->getInfo(['is_company' => 1]);
                if ($data['is_company'] == 1 && !empty($company)) return ['err' => '公司账号只能有一个'];

                $data['longitude'] = $longitude = $data['longitude'] ?? 113.2782112;
                $data['latitude'] = $latitude = $data['latitude'] ?? 23.13512111;
                if (!($longitude > 90 && $longitude < 180 && $latitude > 0 && $latitude < 90)) return ['err' => '经度必须90-180，纬度必须0-90'];
                $data['long_lat_geometry'] = Db::raw("geomfromtext('POINT({$longitude} {$latitude})')");
                $data['create_time'] = time();
                $data['invite_code'] = $data['is_company'] == 1 ? $memberModel->createInviteCode() : '';
                if ($data['real_verify'] == 1) $data['level'] = $levelModel::VERIFIY_LEVEL;  //升级到认证等级

                Db::startTrans();
                $isSave = $mid = $memberModel->add($data);
                if (!$isSave) {
                    Db::rollback();
                    return ['err' => '保存失败，请重试'];
                }

                if ($data['is_company'] == 0) { //有推荐人情况
                    if (empty($recommend_invite_code)) {
                        Db::rollback();
                        return ['err' => '邀请人不能为空'];
                    }
                    $inviteMember = $memberModel->getInfo(['invite_code' => $recommend_invite_code]);
                    if (empty($inviteMember)) {
                        Db::rollback();
                        return ['err' => '邀请人不存在'];
                    }

                    if ($data['identity'] == $memberModel::PARTNER) {
                        $up_partner = $memberModel->getList(['id' => explode(',', $inviteMember['recommend_str']), 'identity' => $memberModel::PARTNER], 0);
                        if ($up_partner) return ['err' => '上级存在合伙人，不能设置成合伙人'];
                    }


                    if ($inviteMember['status'] == 0) return ['err' => '邀请人被禁用'];
                    if ($inviteMember['is_company'] == 0 && $inviteMember['parent_id'] == 0) return ['err' => '邀请人无推荐人'];

                    //更新单前用户的关系
                    $update_data = [
                        'parent_id' => $inviteMember['id'],
                        'recommend_dept' => $inviteMember['recommend_dept'] + 1,
                        'recommend_str' => empty($inviteMember['recommend_str']) ? $mid : $mid . ',' . $inviteMember['recommend_str'],
                        'invite_code' => $memberModel->createInviteCode()
                    ];

                    if ($inviteMember['type'] == 1) { //内部用户
                        $update_data['type'] = 2; //生成种子用户
                        //更新内部用户邀请码
                        $invite_update_res = $memberModel->editByID($inviteMember['id'], ['invite_code' => $memberModel->createInviteCode()]);
                        if (!$invite_update_res) {
                            Db::rollback();
                            return ['err' => '更新内部用户邀请码失败'];
                        }
                    }

                    $isSave = $memberModel->editByID($mid, $update_data);
                    if (!$isSave) {
                        Db::rollback();
                        return ['err' => '邀请出错1'];
                    }

                    //更新推荐人，直推数量
                    $res = $memberModel->setValIncByID($inviteMember['id'], 'recommend_num', 1);
                    if (!$res) {
                        Db::rollback();
                        return ['err' => '更新推荐人失败'];
                    }

                    //注册赠送套餐
                    $packageLogic = model('common/package/PackageLogic', 'logic');
                    $give_res = $packageLogic->givePackage($mid, $packageLogic::REGISTER_GIVE);
                    if ($give_res['code'] != SUCCESS) {
                        Db::rollback();
                        return ['err' => $give_res['msg']];
                    }


                } else {  //无推荐人情况
                    $isSave = $memberModel->editByID($mid, ['recommend_str' => $mid]);
                    if (!$isSave) {
                        Db::rollback();
                        return ['err' => '保持失败'];
                    }
                }
                (new \easemob\EasemobIm())->createUser($mid, $data['nickname'], md5($mid . 'aawwff'));
                model('common/EasemoblmLogic', 'logic')->joinSysGroup($mid);
            }
            Db::commit();
            return ['ret' => '保存成功'];
        }
        $city = $district = $data = array();


        if (input('?get.id')) {
            $data = $memberModel->getInfo(['id' => input('get.id/d')]);
            if ($data) $data['recommend_invite_code'] = $data['parent_id'] == 0 ? '' : $memberModel->getValByID($data['parent_id'], 'invite_code');
        } else {
            if (input('?get.random')) {
                $data = $this->randomMember();
            }
        }

        $areaModel = model('common/area/Area');
        $province = array_column($areaModel->getList(['dept' => 1], 0), 'name', 'id');

        if (isset($data['province'])) $city = array_column($areaModel->getList(['pid' => $data['province']], 0), 'name', 'id');
        if (isset($data['city'])) $district = array_column($areaModel->getList(['pid' => $data['city']], 0), 'name', 'id');

        $content_type_list = model('common/content/Category')->getList(['hide' => 0], 0, 'name');
        $content_types = isset($data['content_types']) ? trimValue(explode('/', $data['content_types'])) : [];
        foreach ($content_type_list as &$content_type) {
            $content_type['checked'] = in_array($content_type['name'], $content_types) ? 1 : 0;
        }

        $expect_object_list = model('common/member/Label')->getList(['is_hide' => 0, 'type' => 2], 0, 'name');
        $expect_objects = isset($data['expect_object']) ? trimValue(explode('/', $data['expect_object'])) : [];

        foreach ($expect_object_list as &$expect_object) {
            $expect_object['checked'] = in_array($expect_object['name'], $expect_objects) ? 1 : 0;
        }

        $address = "";
        if (isset($data['latitude']) && isset($data['longitude'])) {
            $currentCityInfo = $areaModel->currentCityInfo($data['latitude'], $data['longitude']);
            $address = ($currentCityInfo['country'] ?? '')
                . ($currentCityInfo['province'] ?? '')
                . ($currentCityInfo['city'] ?? '')
                . ($currentCityInfo['district'] ?? '')
                . ($currentCityInfo['town'] ?? '')
                . ($currentCityInfo['street'] ?? '')
                . ($currentCityInfo['street_number'] ?? '')
                . ($currentCityInfo['direction'] ?? '');
        }

        $this->assign('province', $province);
        $this->assign('city', $city);
        $this->assign('district', $district);
        $this->assign('address', $address);
        $this->assign('name', $data);
        $this->assign('profession_list', model('common/member/Label')->getCol('name', ['is_hide' => 0, 'type' => 1]));
        $this->assign('expect_object_list', $expect_object_list);
        $this->assign('content_type_list', $content_type_list);
        $this->assign('sexs', $memberModel->sexs);
        $this->assign('types', $memberModel->types);
        return $this->fetch();
    }

    public function del()
    {
        if ($this->request->isAjax()) {
            $id = input('post.id/d');
            if ($id) {
                $memberModel = model('common/member/Member');
                $member = $memberModel->getInfo(['id' => $id]);
                if (empty($member)) {
                    return ['err' => '会员不存在或已删除'];
                }
                $isDelete = $memberModel->delByID($id);
                if ($isDelete) {
                    $fileLogic = model('common/file/FileLogic', 'logic');
                    if ($fileLogic->fileExists($member['avatar'])) $fileLogic->deleteFile($member['avatar']);
                    return ['ret' => '删除成功'];
                }
                return ['err' => '删除失败，请重试'];
            }
            return ['err' => 'id参数错误'];
        }
        return ['err' => '提交参数错误'];
    }

    public function getArea()
    {
        $id = input('id/d');
        $areaModel = model('common/area/Area');
        $area = $areaModel->getList(['pid' => $id], 0, 'id,name');
        $area = array_column($area, 'name', 'id');
        return !empty($area) ? json($area) : '{}';
    }

    public function videoVerify()
    {
        $where = [];
        if (input('?get.type')) {
            $type = input('get.type', '');
            switch ($type) {
                // 审核
                case 1:
                    // 通过
                case 2:
                    // 拒绝
                case 3:
                    $where['vv.status'] = $type;
                    break;
                // 用户id
                case 'id':
                    $where['vv.member_id'] = $type;
                    break;
                // 昵称或手机
                default:
                    $text = input('get.text', '');
                    if (!empty($type) && !empty($text)) {
                        $where['member_id'] = model('common/member/Member')->getCol('id', [[$type, 'like', '%' . $text . '%']]);
                    }
            }
        }
        $videoVerifyModel = model('common/member/VideoVerify');
        $this->assign('data', $videoVerifyModel->getVideoVerify($where, 'vv.*, m.avatar, m.nickname, m.sex, m.username', 'id desc'));
        $this->assign('page', $videoVerifyModel->page_info->render());
        return $this->fetch();
    }

    public function updateVerify()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->post();
            $videoVerifyModel = model('common/member/VideoVerify');
            if (empty($data['id']) || empty($data['status'])) {
                return json(['code' => 0, 'msg' => '缺少必要参数']);
            }

            if (!in_array($data['status'], [2, 3])) {
                return json(['code' => 0, 'msg' => '审核状态错误']);
            }

            $verify = $videoVerifyModel->getInfo(['id' => $data['id']]);
            if (empty($verify)) {
                return json(['code' => 0, 'msg' => '认证信息不存在或已删除']);
            }

            if ($verify['status'] != 1 || $verify['review_time'] > 0) {
                return json(['code' => 0, 'msg' => '认证信息状态不允许']);
            }
            $update = [
                'status' => $data['status'],
                'reason' => $data['reason'],
                'review_time' => time()
            ];
            $isUpdate = $videoVerifyModel->edit(['id' => $data['id']], $update);
            if ($isUpdate) {
                return json(['code' => 1, 'msg' => '审核成功']);
            }
            return json(['code' => 0, 'msg' => '审核失败，请再试一次']);
        }
        return json(['code' => 0, 'msg' => '请求方式有误']);
    }

    public function follow()
    {
        $config = [
            'title' => '关注',
            'url' => 'follow',
        ];
        $type = input('get.type', false);
        $text = input('get.text', '');
        $data = model('common/member/FollowBlacklist')->getFollowBlackList(1, $type, $text);
        $this->assign('data', $data);
        $this->assign('config', $config);
        return $this->fetch('follow_blacklist');
    }

    public function blacklist()
    {
        $config = [
            'title' => '拉黑',
            'url' => 'blacklist',
        ];
        $type = input('get.type', false);
        $text = input('get.text', '');
        $data = model('common/member/FollowBlacklist')->getFollowBlackList(2, $type, $text);
        $this->assign('data', $data);
        $this->assign('config', $config);
        return $this->fetch('follow_blacklist');
    }

    public function changeFollowAndBlacklist()
    {
        if ($this->request->isAjax()) {
            $id = input('post.id/d');
            $follow_blacklist = Db::name($this->table . '_follow_blacklist')->where('id', $id)->find();
            if (!$follow_blacklist) {
                return ['err' => '记录不存在'];
            }

            if ($follow_blacklist['status'] == 0) {
                return ['err' => '用户未' . ($follow_blacklist['type'] == 1 ? '关注' : '拉黑')];
            }
            $isUpdate = Db::name($this->table . '_follow_blacklist')
                ->where('id', $follow_blacklist['id'])
                ->update(['status' => 0, 'update_time' => time()]);
            if ($isUpdate) {
                return ['ret' => '删除成功'];
            }
            return ['ret' => '删除失败，请重试'];
        }
        return ['err' => '请求方式有误'];
    }

    public function getVerifySource()
    {
        if ($this->request->isAjax()) {
            $id = input('post.id/d');
            $member_id = input('post.member_id/d');
            if ($id && $member_id) {
                $url = model('common/member/File')->getCol('url', ['table_id' => $id, 'member_id' => $member_id, 'type' => 4]);
                if ($url) {
                    return json($url);
                }
            }
        }
        return '[]';
    }


    /**
     * User:Simony
     * Function: 会员等级列表
     */
    public function level()
    {

        //params
        $field = input('get.field');
        $text = input('get.text');

        //where
        $where = [];
        if ($text) $where[] = [$field, 'like', "%{$text}%"];
//        print_r($where);die;

        //model
        $levelModel = model('common/member/Level');

        //getData
        $data = $levelModel->getList($where, 10, '*', 'level asc');

        //assign
        $this->assign('data', $data);
        $this->assign('page', $levelModel->page_info->render());
        return $this->fetch();
    }

    /**
     * User:Simony
     * Function: 添加修改等级
     * @return mixed
     */
    public function levelAdd()
    {
        //params
        $id = input('param.id/d', '');
        //model
        $levelModel = model('common/member/Level');

        //getData
        $data = $levelModel->getInfoByID($id);


        if ($this->request->isAjax()) {
            //params
            $name = input('post.name');
            $level = input('post.level/d');
            $desc = input('post.desc');
            $is_red = input('post.is_red');

            //judge
            if ($id && !$data) ds_json_encode('err', '数据不存在');

            $isExistLevelInfo = $levelModel->getInfo(['level' => $level]);

            if ($isExistLevelInfo && $isExistLevelInfo['id'] != $id) ds_json_encode('err', '等级' . $level . '已存在，请添加没有的等级');


            //setData
            $data = [
                'name' => $name,
                'level' => $level,
                'desc' => $desc,
                'is_red' => $is_red,
            ];

            if ($id) {
                $data['update_time'] = $data['create_time'] = time();
                $res = $levelModel->edit(['id' => $id], $data);
            } else {
                $data['update_time'] = time();
                $res = $levelModel->add($data);
            }
            $res ? ds_json_encode('ret', '操作成功') : ds_json_encode('err', '操作失败');
        }


        $this->assign('data', $data);
        return $this->fetch();
    }

    /**
     * User:Simony
     * Function: 删除等级
     */
    public function levelDel()
    {
        if ($this->request->isAjax()) {

            //params
            $id = input('post.id/d', '');

            //model
            $levelModel = model('common/member/Level');

            //judge
            if (!$id) ds_json_encode('err', '缺少必要参数');

            //data
            $res = $levelModel->delByID($id);

            $res ? ds_json_encode('ret', '删除成功') : ds_json_encode('err', '删除失败');
        }
        ds_json_encode('err', '请求方式有误');
    }

    public function label()
    {
        $model = model('common/member/Label');
        $this->assign('type', $model->type);
        $where = [];
        if ($type = input('get.type/d', 0)) {
            $where[] = ['type', '=', $type];
        }
        if ($text = input('get.text/s', '')) {
            $where[] = ['name', 'like', "%{$text}%"];
        }
        $data = $model->getList($where);
        $this->assign('data', $data);
        $this->assign('page', $model->page_info->render());
        return $this->fetch();
    }

    public function labelAdd()
    {
        $model = model('common/member/Label');
        if ($this->request->isAjax()) {
            $data = $this->request->post();
            $validate = validate('MemberLabel');
            if (!$validate->check($data)) {
                return ['err' => $validate->getError()];
            }
            $label = $model->getInfo(['name' => $data['name']]);
            if (!empty($label) && ($label['id'] != $data['id'])) {
                return ['err' => '名称不能重复'];
            }
            $id = $data['id'];
            unset($data['id']);
            $data['update_time'] = time();
            if ($id) {
                $isSave = $model->edit(['id' => $id], $data);
            } else {
                $data['create_time'] = $data['update_time'];
                $isSave = $model->add($data);
            }
            if ($isSave) {
                return ['ret' => '保存成功'];
            }
            return ['err' => '保存失败，请再试一次'];
        }
        $id = input('get.id/d');
        $name = [];
        if ($id) {
            $name = $model->getInfo(['id' => $id]);
        }
        $this->assign('name', $name);
        $this->assign('type', $model->type);
        return $this->fetch();
    }


    /**
     * User: Simony
     * Function:上传图片
     * @return mixed
     */
    public function addImage()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->post();

            $member_id = input('param.member_id/d', 0);
            if ($member_id <= 0) return ['err' => '参数错误'];
            if (!isset($data['file']) || empty($data['file'])) return ['err' => '图片不能为空'];


            $img_ids = explode(',', $data['image_ids']);
            $file = $data['file'] ?? [];

            $delete = empty($img_ids) ? array() : array_diff($img_ids, array_keys($file));

            //删除废图片
            $fileModel = model('common/member/File');
            foreach ($delete as $file_id) {
                $file = $fileModel->getInfoByID($file_id);
                if ($file) {
                    $fileModel->delByID($file_id);
                    $fileLogic = model('common/file/FileLogic', 'logic');
                    if ($fileLogic->fileExists($file['url'])) $fileLogic->deleteFile($file['url']);
                }
            }

            $update_all = [];
            if ($file) {
                if ($data['type'] == 3 && $data['red_packet_price'] <= 0) return ['err' => '红包金额必须大于0'];
                foreach ($file as $file_id => $val) {
                    $update_all[] = [
                        'id' => $file_id,
                        'table_id' => $member_id,
                        'member_id' => $member_id,
                        'status' => $val['status'],
                        'remark' => $val['remark'],
                        'type' => $data['type'],
                        'red_packet_price' => $data['type'] == 3 ? $data['red_packet_price'] : 0,
                    ];
                }
            }

            $fileModel->saveAll($update_all);

            return ['ret' => '保存成功'];

        }
        return $this->fetch();
    }

    public function coordinatePicking()
    {
        return $this->fetch();
    }


    /***
     * User: Simony
     * Function:推荐树状图
     */
    public function recommendTree()
    {
        $pid = input('pid/d', 0);
        $memberModel = model('common/member/Member');

        $field = 'm.id,m.username,m.nickname,m.identity,m_l.name as level_name,is_company,parent_id';

        $where = [
            ['m.parent_id', 'eq', $pid],
            ['m.invite_code', 'neq', ''],
        ];
        if ($pid == 0) {
            $where[] = ['is_company', 'eq', 1];
        }


        $list = $memberModel->alias('m')
            ->field($field)
            ->join('member_level m_l', 'm.level=m_l.level')
            ->where($where)
            ->order('m.id asc')->select();
//        echo $memberModel->getLastSql();die;

        if ($this->request->isAjax()) return json_encode(['status' => 1, 'msg' => '获取成功', 'data' => $list]);

        //assign
        $this->assign('list', $list);
        $this->assign('identitys', $memberModel->identitys);

        return $this->fetch();
    }


    public function randomMember()
    {
        //职业
        $profession_name_list = model('common/member/Label')->getCol('name', ['is_hide' => 0, 'type' => 1]);
        $profession = $profession_name_list[mt_rand(0, count($profession_name_list) - 1)];

        //交友对象
        $content_type_name_list = model('common/content/Category')->getCol('name', ['hide' => 0]);
        shuffle($content_type_name_list);
        $content_types = implode('/', array_slice($content_type_name_list, 0, mt_rand(1, count($content_type_name_list))));


        //期望对象
        $expect_object_name_list = model('common/member/Label')->getCol('name', ['is_hide' => 0, 'type' => 2]);
        shuffle($expect_object_name_list);
        $expect_object = implode('/', array_slice($expect_object_name_list, 0, mt_rand(1, count($expect_object_name_list))));


        //出生日期
        $birthday = date('Y-m-d', time() - mt_rand(1, 40) * 365 * 86400);

        //邀请码 随机是公司
        $memberModel = model('common/member/Member');
        $recommend_invite_code = $memberModel->getVal('invite_code', ['is_company' => 1]);

        //手机号
        $username = '';
        $mobile_arr = ['130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '144', '147', '150', '151', '152', '153', '155', '156', '157', '158', '159', '176', '177', '178', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189',];
        $mobile_arr_count = count($mobile_arr);
        while (true) {
            $mobile = $mobile_arr[mt_rand(0, $mobile_arr_count - 1)] . randStr(8);
            $member = $memberModel->getInfo(['username' => $mobile]);
            if (empty($member)) {
                $username = $mobile;
                break;
            }
        }

        //性别
        $sex = mt_rand(1, 2);

        //昵称
        $xing = [
            '赵', '钱', '孙', '李', '周', '吴', '郑', '王', '冯', '陈', '褚', '卫', '蒋', '沈', '韩', '杨', '朱', '秦', '尤', '许', '何', '吕', '施', '张', '孔', '曹', '严', '华', '金', '魏', '陶', '姜', '戚', '谢', '邹', '喻', '柏', '水', '窦', '章', '云', '苏', '潘', '葛', '奚', '范', '彭', '郎', '鲁', '韦', '昌', '马', '苗', '凤', '花', '方', '任', '袁', '柳', '鲍', '史', '唐', '费', '薛', '雷', '贺', '倪', '汤', '滕', '殷', '罗', '毕', '郝', '安', '常', '傅', '卞', '齐', '元', '顾', '孟', '平', '黄', '穆', '萧', '尹', '姚', '邵', '湛', '汪', '祁', '毛', '狄', '米', '伏', '成', '戴', '谈', '宋', '茅', '庞', '熊', '纪', '舒', '屈', '项', '祝', '董', '梁', '杜', '阮', '蓝', '闵', '季', '贾', '路', '娄', '江', '童', '颜', '郭', '梅', '盛', '林', '钟', '徐', '邱', '骆', '高', '夏', '蔡', '田', '樊', '胡', '凌', '霍', '虞', '万', '支', '柯', '管', '卢', '莫', '柯', '房', '裘', '缪', '解', '应', '宗', '丁', '宣', '邓', '单', '杭', '洪', '包', '诸', '左', '石', '崔', '吉', '龚', '程', '嵇', '邢', '裴', '陆', '荣', '翁', '荀', '于', '惠', '甄', '曲', '封', '储', '仲', '伊', '宁', '仇', '甘', '武', '符', '刘', '景', '詹', '龙', '叶', '幸', '司', '黎', '溥', '印', '怀', '蒲', '邰', '从', '索', '赖', '卓', '屠', '池', '乔', '胥', '闻', '莘', '党', '翟', '谭', '贡', '劳', '逄', '姬', '申', '扶', '堵', '冉', '宰', '雍', '桑', '寿', '通', '燕', '浦', '尚', '农', '温', '别', '庄', '晏', '柴', '瞿', '阎', '连', '习', '容', '向', '古', '易', '廖', '庾', '终', '步', '都', '耿', '满', '弘', '匡', '国', '文', '寇', '广', '禄', '阙', '东', '欧', '利', '师', '巩', '聂', '关', '荆',
            '司马', '上官', '欧阳', '夏侯', '诸葛', '闻人', '东方', '赫连', '皇甫', '尉迟', '公羊', '澹台', '公冶', '宗政', '濮阳', '淳于', '单于', '太叔', '申屠', '公孙', '仲孙', '轩辕', '令狐', '徐离', '宇文', '长孙', '慕容', '司徒', '司空'
        ];
        //男名
        $ming_1 = ['伟', '刚', '勇', '毅', '俊', '峰', '强', '军', '平', '保', '东', '文', '辉', '力', '明', '永', '健', '世', '广', '志', '义', '兴', '良', '海', '山', '仁', '波', '宁', '贵', '福', '生', '龙', '元', '全', '国', '胜', '学', '祥', '才', '发', '武', '新', '利', '清', '飞', '彬', '富', '顺', '信', '子', '杰', '涛', '昌', '成', '康', '星', '光', '天', '达', '安', '岩', '中', '茂', '进', '林', '有', '坚', '和', '彪', '博', '诚', '先', '敬', '震', '振', '壮', '会', '思', '群', '豪', '心', '邦', '承', '乐', '绍', '功', '松', '善', '厚', '庆', '磊', '民', '友', '裕', '河', '哲', '江', '超', '浩', '亮', '政', '谦', '亨', '奇', '固', '之', '轮', '翰', '朗', '伯', '宏', '言', '若', '鸣', '朋', '斌', '梁', '栋', '维', '启', '克', '伦', '翔', '旭', '鹏', '泽', '晨', '辰', '士', '以', '建', '家', '致', '树', '炎', '德', '行', '时', '泰', '盛', '雄', '琛', '钧', '冠', '策', '腾', '楠', '榕', '风', '航', '弘'];
        // 女名
        $ming_2 = ['秀', '娟', '英', '华', '慧', '巧', '美', '娜', '静', '淑', '惠', '珠', '翠', '雅', '芝', '玉', '萍', '红', '娥', '玲', '芬', '芳', '燕', '彩', '春', '菊', '兰', '凤', '洁', '梅', '琳', '素', '云', '莲', '真', '环', '雪', '荣', '爱', '妹', '霞', '香', '月', '莺', '媛', '艳', '瑞', '凡', '佳', '嘉', '琼', '勤', '珍', '贞', '莉', '桂', '娣', '叶', '璧', '璐', '娅', '琦', '晶', '妍', '茜', '秋', '珊', '莎', '锦', '黛', '青', '倩', '婷', '姣', '婉', '娴', '瑾', '颖', '露', '瑶', '怡', '婵', '雁', '蓓', '纨', '仪', '荷', '丹', '蓉', '眉', '君', '琴', '蕊', '薇', '菁', '梦', '岚', '苑', '婕', '馨', '瑗', '琰', '韵', '融', '园', '艺', '咏', '卿', '聪', '澜', '纯', '毓', '悦', '昭', '冰', '爽', '琬', '茗', '羽', '希', '欣', '飘', '育', '滢', '馥', '筠', '柔', '竹', '霭', '凝', '晓', '欢', '霄', '枫', '芸', '菲', '寒', '伊', '亚', '宜', '可', '姬', '舒', '影', '荔', '枝', '丽', '阳', '妮', '宝', '贝', '初', '程', '梵', '罡', '恒', '鸿', '桦', '骅', '剑', '娇', '纪', '宽', '苛', '灵', '玛', '媚', '琪', '晴', '容', '睿', '烁', '堂', '唯', '威', '韦', '雯', '苇', '萱', '阅', '彦', '宇', '雨', '洋', '忠', '宗', '曼', '紫', '逸', '贤', '蝶', '菡', '绿', '蓝', '儿', '翠', '烟'];

        $ming_str = 'ming_' . $sex;
        $ming = $$ming_str; //名

        // 单字名
        $m = $ming[mt_rand(0, count($ming) - 1)];
        // 双字名
        mt_rand(0, 1) && $m .= $ming[mt_rand(0, count($ming) - 1)];
        $nickname = $xing[mt_rand(0, count($xing) - 1)] . $m;


        $data = [
            'username' => $username, //手机号
            'nickname' => $nickname, //昵称
            'birthday' => $birthday,
            'wechat' => randStr(mt_rand(5, 8), 2),
            'sex' => $sex,
            'wechat_hide' => 1,
            'height' => mt_rand(139, 191),
            'weight' => mt_rand(40, 91),
            'profession' => $profession,
            'content_types' => $content_types,
            'expect_object' => $expect_object,
            'recommend_invite_code' => $recommend_invite_code, //默认公司
        ];


        return $data;
    }


    /**
     * User:Simony
     * Function: 申请邀请码表列表
     * @return mixed
     */
    public function applyList()
    {
        //params
        $type = input('get.type', '');
        $field = input('get.field', '');
        $value = input('get.value', '');

        //where
        $where = [];
        if ($field) $where[] = [$field, 'eq', $value];
        switch ($type) {
            case 1: //今日
                $where[] = ['apply_time', 'gt', strtotime(date('Y-m-d'))];
                break;
            case 2: //初审
                $where[] = Db::raw('m_a.id=c_t.min_id');
                break;
            case 3://复审
                $where[] = Db::raw('m_a.id<>c_t.min_id');
                break;
        }


        //model
        $memberApplyModel = model('common/member/MemberApply');

        //getData
        $list = $memberApplyModel->getMemberApplyList($where, 10, 'm_a.*,a.name as city_name', 'm_a.id desc');

        //assign
        $this->assign('list', $list);
        $this->assign('page', $memberApplyModel->page_info->render());
        $this->assign('handle_count', $memberApplyModel->getCount([['state', 'neq', 0]]));
        $this->assign('states', $memberApplyModel->states);
        $this->assign('sexs', model('common/member/Member')->sexs);
        return $this->fetch();
    }


    /**
     * User:Simony
     * Function: 申请邀请码表添加修改
     */
    public function applyAdd()
    {
        //params
        $id = input('param.id/d', '');

        //model
        $memberApplyModel = model('common/member/MemberApply');
        $data = $memberApplyModel->getInfoByID($id);


        $memberModel = model('common/member/Member');

        if ($this->request->isAjax()) {
            //post params
            if ($id && !$data) ds_json_encode('err', '数据不存在');
            $ajax_data = $this->request->post();

            if (empty($ajax_data['state'])) ds_json_encode('ret', '请勿重复处理数据');

            $member = $memberModel->getInfoByID($data['member_id']);
            $invite_code = $member['invite_code'];

            if (!empty($invite_code)) {
                $res = $memberApplyModel->edit(['id' => $id], ['state' => 3]);
                $res ? ds_json_encode('ret', '已激活') : ds_json_encode('err', '操作失败');
            }

            Db::startTrans();
            if ($ajax_data['state'] == 1) { //通过
                $inviteMember = $memberModel->getInfo(['invite_code' => $ajax_data['set_invite_code']]);
                if (empty($inviteMember)) ds_json_encode('err', '邀请人不存在');
                if ($inviteMember['status'] == 0) ds_json_encode('err', '邀请人被禁用');
                $send_content = '恭喜您通过' . sysConfig('site_name') . '的激活申请';
                $res = model('common/member/MemberLogic', 'logic')->setInviteCode($member['id'], $ajax_data['set_invite_code']);
                if (!$res) {
                    Db::rollback();
                    ds_json_encode('err', $res['msg']);
                }
                $ajax_data['reason'] = '';
            } else {
                $ajax_data['set_invite_code'] = '';
                $send_content = $ajax_data['reason'];
            }

            //发送短信+推送消息
            if (isset($ajax_data['app_send']) && $ajax_data['app_send'] == 1) { //app
                model('common/Noticle', 'logic')->sendTxtSysNotice($data['member_id'], $send_content, 8, 'users', ['state' => $ajax_data['state']]);
            }
            if (isset($ajax_data['sms_send']) && $ajax_data['sms_send'] == 1) { //sms
                if ($ajax_data['state'] == 1) {
                    $sms_res = SmsService::send($member['username'], SmsService::SMS_APPLY_INVITE_CODE_SUCCESS, null, true);
                } elseif ($ajax_data['state'] == 2) {
                    $sms_res = SmsService::send($member['username'], SmsService::SMS_APPLY_INVITE_CODE_FAIL, $send_content, true);
                }

            }

            $res = $memberApplyModel->edit(['id' => $id], $ajax_data);
            if (!$res) {
                Db::rollback();
                ds_json_encode('err', '操作失败');
            }

            Db::commit();
            ds_json_encode('ret', '操作成功' . (isset($sms_res['status']) && $sms_res['status'] == false ? $sms_res['msg'] : ''));
        }

        if (empty($data['set_invite_code'])) {
            $data['set_invite_code'] = $memberModel->getVal('invite_code', ['is_company' => 1]);

        }


        $this->assign('data', $data);
        $this->assign('states', $memberApplyModel->states);
        $this->assign('sexs', $memberModel->sexs);
        return $this->fetch();
    }

    /**
     * User: Simony
     * Function:
     */
    public function delAllApply()
    {
        $states = input('param.state/s', '');
        if (empty($states)) ds_json_encode('err', '删除条件错误');

        $memberApplyModel = model('common/member/MemberApply');
        $res = $memberApplyModel->del(['state' => explode(',', $states)]);

        $res ? ds_json_encode('ret', '删除成功') : ds_json_encode('err', '删除失败');
    }


    public function updateToken()
    {
        if ($this->request->isAjax()) {
            $id = input('param.id/d', '');
            $memberModel = model('common/member/Member');
            $username = $memberModel->getValByID($id, 'username');
            if ($username) {
                $tokenLogic = model('common/member/TokenLogic', 'logic');
                $tokenLogic->getToken(null, $username, time() - $tokenLogic->generation_time - rand(0, 3600 * 5));//最后操作时间以及token生成时间随机5个钟之内
            }
            ds_json(200, '操作成功');
        }
        return $this->fetch();
    }
}
